<template>
  <div class="message-list-modal" @click.self="emit('close')">
    <div class="message-list-content">
      <div class="message-header">
        <h3>私信</h3>
        <button @click="emit('close')" class="close-btn">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>

      <div class="message-tabs">
        <button 
          :class="{ active: activeTab === 'unread' }"
          @click="activeTab = 'unread'"
        >
          未读 <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
        </button>
        <button 
          :class="{ active: activeTab === 'all' }"
          @click="activeTab = 'all'"
        >
          全部
        </button>
      </div>

      <div class="message-body">
        <div v-if="loading" class="loading">
          <svg viewBox="0 0 24 24" width="40" height="40" fill="currentColor" class="spin">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
          </svg>
          <p>加载中...</p>
        </div>

        <div v-else-if="displayConversations.length === 0" class="empty">
          <svg viewBox="0 0 24 24" width="64" height="64" fill="currentColor" opacity="0.3">
            <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
          </svg>
          <p>{{ activeTab === 'unread' ? '暂无未读私信' : '暂无私信' }}</p>
        </div>

        <div v-else class="conversation-list">
          <div 
            v-for="conv in displayConversations" 
            :key="conv.id"
            class="conversation-item"
            :class="{ unread: conv.unreadCount > 0 }"
            @click="openConversation(conv)"
          >
            <div class="conv-avatar">
              <img 
                v-if="conv.otherUser.avatar" 
                :src="getAvatarUrl(conv.otherUser.avatar)" 
                alt="头像"
              />
              <span v-else class="avatar-placeholder">
                {{ conv.otherUser.nickname?.charAt(0) || 'U' }}
              </span>
              <span v-if="conv.unreadCount > 0" class="unread-dot"></span>
            </div>

            <div class="conv-content">
              <div class="conv-header">
                <span class="conv-name">{{ conv.otherUser.nickname }}</span>
                <span class="conv-time">{{ formatTime(conv.lastMessageTime) }}</span>
              </div>
              <div class="conv-message">
                {{ conv.lastMessage }}
              </div>
            </div>

            <div v-if="conv.unreadCount > 0" class="conv-badge">
              {{ conv.unreadCount }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getConversations } from '../api/message'
import { getAvatarUrl } from '../utils/url'
import { wsManager } from '../utils/websocket'

const emit = defineEmits(['close', 'openChat'])

const activeTab = ref('unread')
const conversations = ref([])
const loading = ref(false)

const unreadCount = computed(() => {
  return conversations.value.reduce((sum, conv) => sum + conv.unreadCount, 0)
})

const displayConversations = computed(() => {
  if (activeTab.value === 'unread') {
    return conversations.value.filter(conv => conv.unreadCount > 0)
  }
  return conversations.value
})

onMounted(() => {
  loadConversations()
  setupWebSocketListeners()
})

onUnmounted(() => {
  removeWebSocketListeners()
})

// 设置 WebSocket 消息监听
function setupWebSocketListeners() {
  // 监听新消息，更新会话列表
  wsManager.on('newMessage', handleNewMessage)
}

// 移除 WebSocket 监听器
function removeWebSocketListeners() {
  wsManager.off('newMessage', handleNewMessage)
}

// 处理接收到的新消息
async function handleNewMessage(data) {
  // 重新加载会话列表以更新未读数和最后一条消息
  await loadConversations(false)
}

async function loadConversations(showLoading = true) {
  if (showLoading) {
    loading.value = true
  }
  try {
    const res = await getConversations()
    if (res.code === 200) {
      conversations.value = res.data.list || []
    }
  } catch (error) {
    // 仅在首次加载时显示错误，避免打扰用户
    if (showLoading) {
      console.error('获取私信列表失败:', error)
    }
    // 模拟数据
    conversations.value = [
      {
        id: 1,
        otherUser: {
          id: 2,
          nickname: '张三',
          avatar: null
        },
        lastMessage: '你好，我想请教一个数学问题...',
        lastMessageTime: new Date().toISOString(),
        unreadCount: 2
      },
      {
        id: 2,
        otherUser: {
          id: 3,
          nickname: '李四',
          avatar: null
        },
        lastMessage: '感谢你的解答！',
        lastMessageTime: new Date(Date.now() - 3600000).toISOString(),
        unreadCount: 0
      }
    ]
  } finally {
    loading.value = false
  }
}

function openConversation(conv) {
  emit('openChat', conv.otherUser)
}

function formatTime(timeStr) {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return time.toLocaleDateString()
  }
}
</script>

<style scoped lang="scss">
.message-list-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .message-list-content {
    width: 90%;
    max-width: 600px;
    height: 80vh;
    max-height: 700px;
    background: white;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .message-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px;
      border-bottom: 1px solid #eee;
      
      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #24292f;
      }
      
      .close-btn {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: transparent;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        color: #57606a;
        transition: all 0.2s;
        
        &:hover {
          background: #f6f8fa;
          color: #24292f;
        }
      }
    }
    
    .message-tabs {
      display: flex;
      padding: 0 20px;
      border-bottom: 1px solid #eee;
      
      button {
        padding: 12px 20px;
        background: transparent;
        border: none;
        border-bottom: 2px solid transparent;
        font-size: 14px;
        color: #57606a;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        gap: 6px;
        
        &.active {
          color: #667eea;
          border-bottom-color: #667eea;
          font-weight: 500;
        }
        
        &:hover:not(.active) {
          color: #24292f;
        }
        
        .badge {
          background: #ff4d4f;
          color: white;
          font-size: 12px;
          padding: 2px 6px;
          border-radius: 10px;
          min-width: 18px;
          text-align: center;
        }
      }
    }
    
    .message-body {
      flex: 1;
      overflow-y: auto;
      
      .loading,
      .empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #8c959f;
        
        svg.spin {
          animation: spin 1s linear infinite;
          color: #667eea;
          margin-bottom: 16px;
        }
        
        p {
          margin: 16px 0 0 0;
          font-size: 14px;
        }
      }
      
      .conversation-list {
        .conversation-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 16px 20px;
          cursor: pointer;
          transition: background 0.2s;
          border-bottom: 1px solid #f6f8fa;
          
          &:hover {
            background: #f6f8fa;
          }
          
          &.unread {
            background: #f0f6ff;
            
            .conv-message {
              font-weight: 500;
              color: #24292f;
            }
          }
          
          .conv-avatar {
            width: 48px;
            height: 48px;
            flex-shrink: 0;
            position: relative;
            
            img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
              object-fit: cover;
            }
            
            .avatar-placeholder {
              width: 100%;
              height: 100%;
              border-radius: 50%;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 18px;
              font-weight: bold;
            }
            
            .unread-dot {
              position: absolute;
              top: 0;
              right: 0;
              width: 12px;
              height: 12px;
              background: #ff4d4f;
              border: 2px solid white;
              border-radius: 50%;
            }
          }
          
          .conv-content {
            flex: 1;
            min-width: 0;
            
            .conv-header {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 4px;
              
              .conv-name {
                font-size: 15px;
                font-weight: 500;
                color: #24292f;
              }
              
              .conv-time {
                font-size: 12px;
                color: #8c959f;
                flex-shrink: 0;
              }
            }
            
            .conv-message {
              font-size: 13px;
              color: #57606a;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          
          .conv-badge {
            flex-shrink: 0;
            background: #ff4d4f;
            color: white;
            font-size: 12px;
            font-weight: 500;
            padding: 2px 8px;
            border-radius: 10px;
            min-width: 20px;
            text-align: center;
          }
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

